import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, getUserProfile, getUserDetailById } from '@/api/user'
import { resetRouter } from '@/router'
const state = {
  token: getToken() || '', // 用户token 默认null
  userInfo: {}
}

const mutations = {
  // 设置token
  getToken(state, token) {
    state.token = token
    // 将token存储到本地
    setToken(token)
  },
  // 移除token
  removeToken(state) {
    state.token = ''
    // 本地删除token
    removeToken()
  },
  // 设置用户信息
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  // 删除用户信息
  removeUserInfo(state) {
    state.userInfo = {}
  }
}

const actions = {
  // 登录逻辑 异步获取数据
  async  loginAction(context, data) {
    const res = await login(data)
    context.commit('getToken', res.data)
  },
  // 异步获取用户信息
  async getUserInfo(context) {
    const res = await getUserProfile()
    const detailInfo = await getUserDetailById(res.data.userId)
    context.commit('setUserInfo', { ...res.data, ...detailInfo.data })
    // console.log(res)
    return res.data.roles.menus
  },
  // 退出登录
  logout(context) {
    context.commit('removeToken')
    context.commit('removeUserInfo')
    resetRouter() // 退出后清除动态路由
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
